package cn.itcast.Servlet;

import cn.itcast.domain.User;
import cn.itcast.utils.JDBCUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //获取注册时候的username和password
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        double yue = Double.parseDouble(request.getParameter("yue"));
        Connection conn=null;
        PreparedStatement pst=null;
        //如果用户名的长度不为0
        if (username.length()!=0){
            //如果密码的长度在6到10位之间 可以注册
            if (password.length()>=6 && password.length()<=10){
                //注册逻辑
                try {
                    conn=JDBCUtils.getConnection();
                    String sql="insert into user values(?,?,?)";
                    pst=conn.prepareStatement(sql);
                    pst.setString(1,username);
                    pst.setString(2,password);
                    pst.setDouble(3,yue);
                    pst.executeUpdate();
                    response.getWriter().write("恭喜你注册成功");
                    response.getWriter().write("<a href='login.jsp'>登录页面</a>\n");
                    return;
                } catch (SQLException e) {
                    e.printStackTrace();
                    response.getWriter().write("注册失败,用户名唯一");
                    response.getWriter().write("<a href='register.jsp'>登录页面</a>\n");
                    return;
                }finally {
                    JDBCUtils.close(conn,pst);
                }
            }else {
                response.getWriter().write("注册失败,密码应该在6到10位");
                response.getWriter().write("<a href='register.jsp'>登录页面</a>\n");
                return;
            }
        }else {
            response.getWriter().write("注册失败,用户名不能为空<br>");
            response.getWriter().write("<a href='register.jsp'>登录页面</a>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
